#!/usr/bin/env python3
#
# Software License Agreement (MIT License)
# Author: Duke Fong <d@d-l.io>

import cgi, sys, os, json
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from conf.gconf import gconf

if len(sys.argv) == 1:
    print('Content-Type: application/json; charset=utf-8\n')

articles = []

for url in os.listdir('../articles'):
    article_dir = '../articles/' + url

    with open(article_dir + '/_metadata', 'r') as file:
        metadata = json.loads(file.read())
    metadata = {'url': url, **metadata} # put the url at the top

    if os.path.exists(article_dir + '/summary.md'):
        with open(article_dir + '/summary.md', 'r') as file:
            metadata['summary'] = file.read()

    if os.path.exists(article_dir + '/_count'):
        with open(article_dir + '/_count', 'r') as file:
            metadata['count'] = int(file.read())
    else:
        metadata['count'] = 0
    articles.append(metadata)

articles.sort(key=lambda x: x['date'], reverse=True)
print(json.dumps(articles, indent=2, ensure_ascii=False, sort_keys=False))

